package com.xuecheng.checkcode.service.impl;

import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.checkcode.model.CheckCodeResultDto;
import com.xuecheng.checkcode.service.CheckCodeService;
import com.xuecheng.checkcode.service.SendCodeService;
import com.xuecheng.checkcode.utils.MailUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.mail.MessagingException;

@Slf4j
@Service
public class SendCodeServiceImpl implements SendCodeService {

    @Autowired
    private RedisCheckCodeStore redisCheckCodeStore;

    /**
     * 发送邮件验证码
     *
     * @param email 邮箱号
     * @param code  验证码
     * @return 验证码返回结果嘞
     */
    @Override
    public CheckCodeResultDto sendCode(String email, String code) {
        // 调用自定义的邮箱发送验证码工具类
        try {
            MailUtils.sendTestMail(email, code);
        } catch (MessagingException e) {
            log.debug("邮件发送失败：{}", e.getMessage());
            XueChengPlusException.cast("发送验证码失败，请稍后再试");
        }
        // 存储验证码到redis中(有效期3分钟)，用于后期登录时候校验
        redisCheckCodeStore.set(email, code, 180);
        // 将验证码key存入返回值中，返回给前端
        CheckCodeResultDto checkCodeResultDto = new CheckCodeResultDto();
        checkCodeResultDto.setKey(email);
        return checkCodeResultDto;
    }
}
